package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    //分页查询  /employee/list.响应HTML 内容
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model){

        //分页查询数据
        PageResult<Employee> pageResult = employeeService.query(qo);
        //存到model中
        model.addAttribute("pageResult",pageResult);

        //查询所有部门
        List<Department> departments = departmentService.listAll();
        //存到model中
        model.addAttribute("departments",departments);
        //返回视图文件路径
        return "/employee/list";
    }

    //删除 /employee/delete?id=1
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null) {
            employeeService.delete(id);
        }
        //重定向
        return "redirect:/employee/list";
    }

    // 增加和修改 /employee/input
    @RequestMapping("/input")
    public String input(Long id, Model model){
        //查询所有部门
        List<Department> departments = departmentService.listAll();
        //存到model中
        model.addAttribute("departments",departments);
        if (id != null) {
            //去修改
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "employee/input";
    }

    //   /employee/saveOrUpdate  参数在请求体中
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee){
        if (employee.getId() == null){
            employeeService.save(employee);
        }else {
            employeeService.update(employee);
        }
        //重定向
        return "redirect:/employee/list";
    }


}
